package com.hf.easypoi;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @program: testjar
 * @description: easypoi 的整合类
 * @author: hfen
 * @create: 2020-03-16 11:02
 **/
public class EasyPoiUtils {

    /**
     * 1. 新建savefile文件夹,用于保存文件
     * 2. 将dataset写入workbook
     * 3. 新建输出流 fos FileOutputStream
     * 4. 将workbook 写入fos
    * @Description: 导出Excel
    * @Param: [pojoClass, dataSet, path, filename]
    * @return: void
    * @Author: hfen
    * @Date: 2020/3/16 11:05
    */
    public static void exportExcel(Class<?> pojoClass, Collection<?> dataSet, String path, String filename) throws IOException {
        File savefile = new File(path);
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, dataSet);
        FileOutputStream fos = new FileOutputStream(path+filename);
        workbook.write(fos);
        fos.close();
    }

    /**
    * @Description: 将 list的内容，导出到path下，filename的文件中
    * @Param: [list, path, filename]
    * @return: void
    * @Author: hfen
    * @Date: 2020/3/16 11:09
    */
    public static void  exportExcel(List<Map<String, Object>> list, String path, String filename) throws IOException{
        File savefile = new File(path);
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);

        FileOutputStream fos = new FileOutputStream(path+filename);
        workbook.write(fos);
        fos.close();
    }

    public static <T>List<T> importExcel(File file, Class<?> pojoClass, ImportParams params){
        List<T> list = ExcelImportUtil.importExcel(file,UserEntity.class, params);
        return list;
    }
}
